#include "Cats/CatStates/CatState.h"
#include "Cats/CatStates/CatState_Bounce_Skill.h"
#include "Cats/CatSpriteLoader.h"
#include "Cats/BaseCat.h"
#include "Character/Character.h"
#include "Map/GameMap.h"

CatState_Bounce_Skill::CatState_Bounce_Skill(BaseCat* pCatRef):CatState(pCatRef)
{
	_isMovingToUpperLane = true;

	//top and bottom lane bounds
	_mapTopBound = _pGameMapRef->getScreenTopBound();
	_mapBottomBound = _pGameMapRef->getScreenBottomBound() + _pCatRef->boundingBox().size.width/2;

	_exitState = false;
	_isFlanking = false;
}

CatState_Bounce_Skill::~CatState_Bounce_Skill()
{

}

void CatState_Bounce_Skill::onResume()
{
	CatState::onResume();

	//play cat animation
	_pCatRef->stopAllActions();
	_pCatRef->runAction(CatSpriteLoader::getCatAnimation(_pCatRef->getCatType(), CAT_ANIM_WALK));
}


void CatState_Bounce_Skill::runOnEnter()
{
	//random to move up or down at the beginning
	_isMovingToUpperLane = arc4random() % 1;

	//play animation
	_pCatRef->stopAllActions();
	_pCatRef->runAction(CatSpriteLoader::getCatAnimation(_pCatRef->getCatType(), CAT_ANIM_WALK));

}

void CatState_Bounce_Skill::update(float timeDiff)
{
	if (!_exitState) //guard exit to injured state
	{
		//move towards the left
		_pCatRef->move(timeDiff);
		//move up/down the lanes
		lanePositionUpdate(timeDiff);

		//collision detection with the character
		if (_pCatRef->getRect().intersectsRect(_pCharRef->getRect()))
		{
			_exitState = true;
			_isFlanking = false;
			_pCharRef->reduceHealth(_pCatRef->getBaseAttackDamage());
		}

		//out of screen change to flank state
		if (_pCatRef->getPositionX() < -_pCatRef->boundingBox().size.width)
		{
			_exitState = true;
			_isFlanking = true;
		}
	}
	else
	{
		if (_isFlanking)
			_pCatRef->setNextCatState(CAT_FLANK);
		else
			_pCatRef->setNextCatState(CAT_DYING);
	}
}

void CatState_Bounce_Skill::onExit()
{
	CatState::onExit();
	_exitState = false;
	_isFlanking = false;
}

//function for shifting the cat up and down the lanes
void CatState_Bounce_Skill::lanePositionUpdate(float timeDiff)
{
	float yMoveAmount = _pCatRef->getSpeedY() * timeDiff;

	if (_isMovingToUpperLane)
	{
		_pCatRef->setPositionY(_pCatRef->getPositionY() + yMoveAmount);

		if (_pCatRef->getPositionY() >= _mapTopBound)
		{
			_isMovingToUpperLane = false;
			_pCatRef->setPositionY(_mapTopBound);
		}
	}
	else
	{
		_pCatRef->setPositionY(_pCatRef->getPositionY() - yMoveAmount);

		if (_pCatRef->getPositionY() <= _mapBottomBound)
		{
			_isMovingToUpperLane = true;
			_pCatRef->setPositionY(_mapBottomBound);
		}
	}
}
